package lab4.io;

import config.ATMData;
import config.Config;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

public class ServerDelayIO {

    /**
     * Client send 2 commands to server.
     * First - 'get' - to get special object from server
     * Second - 'ok' - when client get this object
     * Server calculate time between the first command and the second
     *
     * @param args
     */
    public static void main(String[] args) {

        long start = System.currentTimeMillis();
        long end;

        try (ServerSocket serverSocket = new ServerSocket(Config.PORT);) {
            System.out.println("Waiting for client on port " + Config.PORT + "...");
            try (
                Socket client = serverSocket.accept()) {
                System.out.println("Just connected to " + client.getRemoteSocketAddress());
                try (
                    ObjectInputStream in = new ObjectInputStream(client.getInputStream());
                    ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream())) {
                    w:
                    while (true) {
                        try {
                            String command = (String) in.readObject();
                            System.out.println("Server: Received command: " + command);

                            switch (command) {
                                case "get":
                                    start = System.currentTimeMillis();
                                    out.writeObject(ATMData.generate());
                                    break;
                                case "ok":
                                    end = System.currentTimeMillis();
                                    System.out.println(end - start);
                                    break;
                                case "exit":
                                    break w;
                            }
                        } catch (SocketTimeoutException s) {
                            System.out.println("Socket timed out!");
                            break;
                        } catch (IOException e) {
                            e.printStackTrace();
                            break;
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                            break;
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}